package mwa.cs.admin.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.SMApplicationLogDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;

/**
 * Servlet implementation class CS86000Srvl
 */
public class CS86000Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private Database db;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS86000Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }

	public void processRequest(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException{
		String vaProcessType = null;
		vaProcessType = request.getParameter("process_type");
		String vaStartDate=null;
		String vaEndDate=null;
		String vaUserName = null;
		
		
		if(request.getParameter("sSearch_0")!=null){
			vaStartDate = request.getParameter("sSearch_0").trim();
		}
		if(request.getParameter("sSearch_1")!=null){
			vaEndDate = request.getParameter("sSearch_1").trim();
		}
		if(request.getParameter("sSearch_2")!=null){
			vaUserName = request.getParameter("sSearch_2").trim();
		}
		
		if(vaProcessType.equals("getDataTable")){
			if(!vaStartDate.equals("")||!vaEndDate.equals("")||!vaUserName.equals("")){
				searchDataTable(request, response,vaStartDate,vaEndDate,vaUserName);
			}
			else{
				getDataTable(request,response);
			}
		}
		else{
			
		}
	}
    
	@SuppressWarnings("unchecked")
	public void searchDataTable(HttpServletRequest request, HttpServletResponse response
			,String vaStartDate,String vaEndDate,String vaUserName) throws ServletException, IOException{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		int  vnSiteId;
		int  vnUserId;
		int vnStart;
		int vnAmount;
		
		//Test
		if(request.getParameter("iDisplayStart") != null){
			vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); 	 // 0
		} else  {
			vnStart = 0;
		}

		if(request.getParameter("iDisplayLength") != null){
			vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
		}else{
			vnAmount = 10;
		}
	
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		
		this.db = new Database();
		SMApplicationLogDAO voSmApplicationLogDAO = new SMApplicationLogDAO(db);
		List<Map<String , Object>> voListSearch;
		vaStartDate = formatDateTimeToString(vaStartDate);
		vaEndDate = formatDateTimeToString(vaEndDate);
//		listSearch = smErrorLogDao.searchData(startDate,endDate,userName,vnStart,vnAmount);
		voListSearch = voSmApplicationLogDAO.searchApplicationLogJoinUserLogin(vaStartDate, vaEndDate,vaUserName , vnStart, vnAmount);
		int start = vnStart+1;
		
		for(int i = 0; i < voListSearch.size() ; i++){ 
			Map<String , Object> mapItem = (Map<String , Object>) voListSearch.get(i);
			voColumn = new JSONArray();
			
			//Count column
			voColumn.add(start);
			String dateTime = (String)mapItem.get("EVENT_DATE")+(String)mapItem.get("EVENT_TIME");
			//DateTime column
			voColumn.add(formatStringToDateTime(dateTime));
			
			//Discription column
			voColumn.add(mapItem.get("LOG_DESCRIPTION"));
			//User name column
			voColumn.add(mapItem.get("USER_NAME"));
			//URL column
			
			voColumn.add(format50TextsPerSpace(mapItem.get("URL_ADDRESS")));
			//Browser column					
			voColumn.add(mapItem.get("AGENT_BROWSER"));
								
			voRow.add(voColumn);
			
			start++;
		}
			voObject.put("iTotalRecords", voListSearch.size());
			voObject.put("iTotalDisplayRecords", voSmApplicationLogDAO.countSearchApplicationLogJoinUserLogin(vaStartDate,vaEndDate,vaUserName));
			db.close();
			voObject.put("aaData", voRow);
			voOut.print(voObject.toJSONString());
	}
	
	
	  public void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8"); 
			response.setContentType("text/JSON");
			
			int  vnSiteId;
			int  vnUserId;
			int vnStart;
			int vnAmount;
			
			//Test
			if(request.getParameter("iDisplayStart") != null){
				vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); 	 // 0
			} else  {
				vnStart = 0;
			}

			if(request.getParameter("iDisplayLength") != null){
				vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
			}else{
				vnAmount = 10;
			}
			//End test
			
			
			JSONObject voObject = new JSONObject();
			JSONArray voRow = new JSONArray();
			JSONArray voColumn = null;
			PrintWriter voOut = response.getWriter();
			
			this.db = new Database();
			SMApplicationLogDAO voSmApplicationLogDAO = new SMApplicationLogDAO(db);
			List<Map<String , Object>> voListFindAll;
			
			int start = vnStart+1;
			voListFindAll = voSmApplicationLogDAO.findAllApplicationLogJoinUserLogin(start,vnAmount);
			
			for(int i = 0; i < voListFindAll.size() ; i++){ 
				Map<String , Object> mapItem = (Map<String , Object>) voListFindAll.get(i);
				voColumn = new JSONArray();
				
				//Count column
				voColumn.add(start);
				String dateTime = (String)mapItem.get("EVENT_DATE")+(String)mapItem.get("EVENT_TIME");
				//DateTime column
				voColumn.add(formatStringToDateTime(dateTime));
				
				//Discription column
				voColumn.add(mapItem.get("LOG_DESCRIPTION"));
				//User name column
				voColumn.add(mapItem.get("USER_NAME"));
				//URL column
				
				voColumn.add(format50TextsPerSpace(mapItem.get("URL_ADDRESS")));
				//Browser column					
				voColumn.add(mapItem.get("AGENT_BROWSER"));
									
				voRow.add(voColumn);
				
				start++;
			}
			
				voObject.put("iTotalRecords", voListFindAll.size());
				voObject.put("iTotalDisplayRecords", voSmApplicationLogDAO.countApplicationLogJoinUserLogin());
				db.close();
				voObject.put("aaData", voRow);
				voOut.print(voObject.toJSONString());
}

    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}
    public String format50TextsPerSpace(Object poText2){
    	String vaText = (String)poText2;
    	if(vaText!=null){
		int lenght = vaText.length()-1;
		for(int i=0;i<=lenght;i++){
			if(i%50==0&&i!=0&&i<=lenght){
				vaText = vaText.substring(0,i)+" "+vaText.substring(i,vaText.length()-1);
			}
		}
    	}
    	return vaText;
    }
    public String formatStringToDateTime(Object poText2){
    	String vaText = (String)poText2;
		String vaYear= vaText.substring(0,4);
		String vaMonth = vaText.substring(4,6);
		String vaDate = vaText.substring(6,8);
		String vaHour = vaText.substring(8,10);
		String vaMinute = vaText.substring(10,12);
		String vaSecond = vaText.substring(12,14);
		vaText = vaDate+"/"+vaMonth+"/"+vaYear+" "+vaHour+":"+vaMinute+":"+vaSecond;   	
		return vaText;
    }
    public String formatDateTimeToString(Object poText2){
    	String vaText = (String)poText2;    	
    	if (vaText != null && !vaText.equals("")) {
    		System.out.println("test1");
    		String vaDate = vaText.substring(0,2);
    		String vaMonth = vaText.substring(3,5);
    		String vaYear= vaText.substring(6,10);
    		vaText = vaYear+vaMonth+vaDate;
    	}
		return vaText;
    }
	

}
